/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package delta.emailer;

import entity.Orders;
import entity.Users;
import facade.UsersFacadeLocal;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author Kate
 */
@Stateless
public class Emailer implements EmailerLocal {

    @EJB
    private UsersFacadeLocal usersFacade;
    String protocol;
    String host;
    String user;
    String pass;
    int port;
    Properties props;
    Session session;

    public Emailer() {
    }

    /**
     *
     * Initiates object with following values: mail server= smtp.gmail.com
     * connects to mail server using account deltaspringproject@gmail.com
     *
     */
    @PostConstruct
    public void postConstruct() {
        user = "deltaspringproject@gmail.com";
        pass = "delta2013";
        protocol = "smtp";
        port = 587;
        host = "smtp.gmail.com";
        // Get system properties
        props = System.getProperties();
        //starttls is required by Google
        props.put("mail.smtp.starttls.enable", "true");
        session = Session.getDefaultInstance(props);

    }

    /**
     * Sends e-mail to many users.
     *
     * @param to recipient e-mail address
     * @param subject e-mail subject
     * @param body e-mail body
     */
    public void sendEmail(Address[] to, String subject, String body) {
        try {
            // Create a MimeMessage object. 
            MimeMessage message = new MimeMessage(session);

            // Set To
            message.addRecipients(Message.RecipientType.TO, to);

            // Set Subject
            message.setSubject(subject);

            // Set the actual message
            message.setText(body);
            sendEmail(message);

        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }

    /**
     * Sends e-mail to one users.
     */
    public void sendEmail(String to, String subject, String body) {
        try {
            InternetAddress address[] = new InternetAddress[1];
            address[0] = new InternetAddress(to);

            sendEmail(address, subject, body);
        } catch (AddressException ex) {
            Logger.getLogger(Emailer.class.getName()).log(Level.SEVERE, null, ex);
        }


    }

    /**
     * Sends e-mail.
     *
     * @param message message to be sent
     */
    public void sendEmail(MimeMessage message) {
        try {
            // Send message
            Transport transport = session.getTransport(protocol);
            transport.connect(host, port, user, pass);

            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }



    }

    private InternetAddress[] getAddress(List<Users> users) throws AddressException {
        InternetAddress emails[];
        emails = new InternetAddress[users.size()];
        int i = 0;
        for (Users user : users) {
            if (user.getEMail() != null) {
                emails[i] = new InternetAddress(user.getEMail());
                i++;
            }
        }
        return emails;
    }

    public void notifyWarehouseEmp(Orders order) {
        List<Users> users;
        InternetAddress emails[];
        String body;
        users = usersFacade.findByRole(2); //finds Warehouse employees

        try {
            emails = getAddress(users);
            body = "Follow the link to watch new order: "
                    + "http://localhost:8082/Delta-war/WarehouseOrders?idOrder="
                    + order.getIdOrder();
            sendEmail(emails, "New order in queue", body);
        } catch (AddressException ex) {
            Logger.getLogger(Emailer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void notifyCourier(Orders order) {
        List<Users> users;
        InternetAddress emails[];
        String body;
        users = usersFacade.findByRole(3); //finds Couriers
        
        try {
            emails = getAddress(users);
            body = "Follow the link to watch new shipped order: "
                    + "http://localhost:8082/Delta-war/courier?idOrder="
                    + order.getIdOrder();
            sendEmail(emails, "New shipped order", body);
        } catch (AddressException ex) {
            Logger.getLogger(Emailer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
     public void notifyCustomer(Orders order) {
        String email=order.getEMail();
        String body;
       if(order.getSubscribe()==1){
            body = "Your order "+ order.getTrackingNumber()+ " was "+order.getOrderStatus();
            sendEmail(email, "Order status changed", body);
       }
       
    }
    
}
